package com.oly.cms.web.controller;

import com.oly.cms.common.domain.entity.CmsColumn;
import com.oly.cms.common.model.properties.OlyThemeConfigProperties;
import com.oly.cms.general.service.cache.GeneralColumnCacheService;
import com.oly.cms.general.service.taglib.ConfigTag;
import com.grace.common.core.controller.BaseController;
import com.grace.common.properties.PropertyEnum;
import com.grace.common.utils.ServletUtils;
import com.grace.common.utils.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;

/** 通用 */
public class CommonController extends BaseController {

    @Autowired
    protected GeneralColumnCacheService cmsColumnService;

    @Autowired
    protected ConfigTag configService;

    /**
     * 默认转发 1.查找是否存在缓存 2.不存在使用默认主题
     *
     * @param page
     * @return
     */
    protected String getPrefix(String themeName, String page, ModelMap mp) {
        setParams(mp);
        if (StringUtils.isNotEmpty(themeName)) {
            boolean support = "true".equals(
                    configService.getKeyDefault(OlyThemeConfigProperties.THEME_CONFIG_GROUP.defaultValue(),
                            OlyThemeConfigProperties.THEME_MORE_INSTALL));
            if (support) {
                return themeName + page;
            }
            return "/web/jump";
        } else {
            return getDefaultThemeName() + page;
        }
    }

    /**
     * 返回参数
     * 
     * @param mp
     */
    private void setParams(ModelMap mp) {
        mp.putAll(ServletUtils.getRequest().getParameterMap());
    }

    /**
     * 获取支持类型
     * 
     * @param themeName
     * @param propertyEnum
     * @return
     */
    protected String getSupportType(String themeName, PropertyEnum propertyEnum) {
        return configService.getKeyDefault(getThemeName(themeName), propertyEnum);
    }

    /**
     * 获取导航信息
     * 
     * @param themeName
     * @param propertyEnum
     * @return
     */
    protected CmsColumn getCmsColumn(String themeName, PropertyEnum propertyEnum) {
        CmsColumn cmsColumn = cmsColumnService.getCmsColumnById(
                Long.parseLong(configService.getKeyDefault(getThemeName(themeName), propertyEnum)));
        return cmsColumn == null ? new CmsColumn() : cmsColumn;
    }

    /**
     * 获取主题名
     * 
     * @param themeName
     * @return
     */
    protected String getThemeName(String themeName) {
        if (StringUtils.isEmpty(themeName)) {
            themeName = getDefaultThemeName();
        }
        return themeName;
    }

    /**
     * 获取默认主题名
     * 
     * @return
     */
    private String getDefaultThemeName() {
        return configService.getKeyDefault(OlyThemeConfigProperties.THEME_CONFIG_GROUP.defaultValue(),
                OlyThemeConfigProperties.THEME_USED);
    }

}
